<?php

    namespace app\listen\controller;

    use app\listen\model\UserLove;
    use app\listen\model\Voice;
    use app\listen\service\MemberService;
    use think\Db;
    use think\Cache;
    use think\Loader;

    class Listen extends \app\common\controller\Base {
        private $memberService;
        private $voiceMod;
        private $loveMod;
        private $commentMod;
        function env() {
            $this->getVoiceMod()->env('pro');
        }
        function getMemberService(): MemberService {
            if (empty($this->memberService)) {
                $this->memberService = new MemberService();
            }
            return $this->memberService;
        }

        /**
         * @return mixed
         */
        public function getLoveMod(): UserLove {
            if (empty($this->loveMod)) {
                $this->loveMod = model('listen/UserLove');
            }

            return $this->loveMod;
        }

        /**
         * @return mixed
         */
        public function getVoiceMod(): Voice {
            if (empty($this->voiceMod)) {
                $this->voiceMod = model('listen/Voice');
            }
            return $this->voiceMod;
        }

        public function getCommentMod(): \app\listen\model\Comment {
            if (empty($this->commentMod)) {
                $this->commentMod = model('listen/Comment');
            }
            return $this->commentMod;

        }

        // 首页
        function index() {
            echo "<p>这是我们的官网</p>";
        }

        // 用户授权认证接口，如果没当前用户没注册，则自动生成一个游客权限的新用户
        public function authorize() {
            $inputJSON = file_get_contents('php://input');
            $input = json_decode($inputJSON, TRUE) ?? [];
            $code = $input['code'] ?? [];
            $secret = '8bd36a96a5da66a781fe7d5c26cdc962';
            $appId = 'wx1e8dd84104228058';
            $env = $input['env']?? 'pro';
            $result = self::https_request('https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code');
            $user = null;
            // 查询openid
            if (!empty($result) && !empty($result->openid)) {
                // 检查游客是否存在
                $user = $this->getMemberService()->findMemberByOpenId($result->openid);
                // 用户不存在
                if (empty($user)) {
                    $user = $this->getMemberService()->registVisitor($result->openid);
                }

            }
            $env = $this->getVoiceMod()->env('pro');
            return api_return(1, ["basePath"=>"https://xrmwl.com",'isTest' => $env['isTest'], 'user' => $user, 'env'=>$env]);
        }

        public function filter($info, $uid, $option = []) {
            if (!empty($info) && !empty($info['list'])) {
                $info['list'] = array_map(function ($value) use ($uid, $option) {
                    if (!empty($value['id'])) {
                        $value['loveCount'] = $this->getLoveMod()->getLoveCount($value['id']);
                        $value['commentCount'] = $this->getCommentMod()->commentCount($value['id']);
                        if (!empty($uid)) {
                            $value['myLove'] = $this->getLoveMod()->getUseLove($uid, $value['id']);
                        }

                        if (isset($value['loveCount']) && !empty($option['lovers'])) {
                            $value['lovers'] = $this->getLoveMod()->getLovers($value['id'], 1, 4);
                        }
                    }

                    return $value;
                }, $info['list']);
            }
            return $info;
        }

        // 详情
        public function detail() {
            $data = $this->getParams();
            $id = $data['id'] ?? null;
            $uid = $data['uid'] ?? null;
            if (!isset($id) || !isset($uid)) {
                return api_return(-2017, 'no id or uid');
            }
            $detail = $this->getVoiceMod()->detail(['id' => $id]);
            $detail = $this->filter($detail, $uid, $data);

            if (false !== $detail) {
                return api_return(10002, $detail);
            } else {
                return api_return(-2017);
            }

        }

        // 获取记录列表
        public function lists() {
            $data = $this->getParams();
            $page = $data['page'] ?? 1;
            $rows = $data['rows'] ?? 10;
            $uid = $data['uid'] ?? null;
            $latitude = $data['latitude'] ?? null;// 维度
            $longitude = $data['longitude'] ?? null;// 经度
            $distance = $data['distance'] ?? 10;// 距离
            if (empty($longitude) || empty($latitude)) {
                return api_return(-2017, 'no latitude or longitude');
            }
            $result = $this->getVoiceMod()->homeList($uid, $page, $rows, $latitude, $longitude, $distance);


            if (false !== $result) {
                $result = $this->filter($result, $uid, $data);
                return api_return(10002, $result);
            } else {
                return api_return(-2017);
            }
        }

        // 获取记录列表
        public function user() {
            $data = $this->getParams();
            // $check = $this->validate($data,'Listen.detail');
            // if($check !==true){
            // 	return api_return($check);
            // }
            $page = $data['page'] ?? 1;
            $rows = $data['rows'] ?? 10;
            $uid = $data['uid'] ?? null;
            $list = $this->getVoiceMod()->userList($uid, $page, $rows);

            if (false !== $list) {
                $list = $this->filter($list, $uid, $data);
                return api_return(10002, $list);
            } else {
                return api_return(-2017);
            }
        }

        // 我的喜欢列表
        public function mylove() {
            $data = $this->getParams();
            $page = $data['page'] ?? 1;
            $rows = $data['rows'] ?? 10;
            $uid = $data['uid'] ?? null;
            $info = $this->getVoiceMod()->myLove($uid, $page, $rows);
            $info = $this->filter($info, $uid, $data);

            if (false !== $info) {
                return api_return(10002, $info);
            } else {
                return api_return(-2017);
            }
        }

        // 获取用户语音被喜欢的总数
        public function loveCount() {
            $data = $this->getParams();
            $uid = $data['uid'] ?? null;
            $count = $this->getVoiceMod()->loveCount($uid);

            if (false !== $count) {
                return api_return(10002, $count);
            } else {
                return api_return(-2017);
            }
        }

        static function createModel($data) {
            if (empty($data)) {
                return ["error" => "no params", "data" => null];
            }
            $voice = [];
            $max = 1000;// 1000毫秒
            // 添加记录的需要变量
            $addKeys = ['uid', 'duration', 'path', 'longitude', 'latitude'];
            // ['path', 'province','city', 'area', 'address', 'longitude', 'dimension', 'direction', 'duration', 'uid', 'addtime']
            foreach ($addKeys as $_key) {
                if (!empty($data[$_key])) {
                    $voice[$_key] = $data[$_key];
                    // 检查秒长度
                    if ($_key === 'duration' && $data[$_key] < $max) {
                        return ["error" => $_key . 'less than 1000ms', "data" => null];
                    }
                } else {
                    return ["error" => $_key, "data" => null];
                }
            };
            $voice['addtime'] = request()->time();

            $voice['audit_status'] = 1;// 暂时默认审核通过
            return ["data" => $voice];
        }

        // 添加记录
        public
        function add_voice() {
            $input = $this->getParams();

            $voice = self::createModel($input);

            if (!empty($voice["error"])) {
                return api_return(-2017, $voice["error"]);
            }
            if (!empty($voice) && !empty($voice['data']) && !empty($voice['data']['path'])) {
                str_replace( "http://", "https://", $voice['data']['path']);
            }
            $res = $this->getVoiceMod()->update_voice($voice['data']);
            if (false !== $res) {
                return api_return(10011, $res);
            } else {
                return api_return(-2017);
            }

        }

        // 更新播放次数
        public function play() {
            $data = $this->getParams();
            if (!empty($data) && !empty($data['id'])) {

                $res = $this->getVoiceMod()->play($data['id']);
                if (false !== $res) {
                    return api_return(10011, $res);
                } else {
                    return api_return(-2017);
                }
            }
        }
        // 更新转发次数
        public function share() {
            $data = $this->getParams();
            if (!empty($data) && !empty($data['id'])) {

                $res = $this->getVoiceMod()->share($data['id']);
                if (false !== $res) {
                    return api_return(10011, $res);
                } else {
                    return api_return(-2017);
                }
            }
        }

        // 移除
        public function del() {
            $data = $this->getParams();
            $id = $data['id'] ?? null;
            if (isset($id)) {
                $res = $this->getVoiceMod()->where('id', $id)->delete();
            } else {
                $res = false;
            }
            if (false !== $res) {
                return api_return(10011, $res);
            } else {
                return api_return(-2017);
            }
        }

        // 喜欢
        public function love() {

            $data = $this->getParams();
            $recipientUid = $data['recipientUid'] ?? null;
            $voiceId = $data['voiceId'] ?? null;
            $uid = $data['uid']??null;

            if (!empty($data) && !empty($voiceId) && !empty($uid)) {

                $res = $this->getLoveMod()->love($uid, $voiceId);

                if (false !== $res) {
                    $value = [];
                    if ($res > 0 && isset($recipientUid)) {
                        // 通知消息,类型喜欢
                        self::https_request($_SERVER['HTTP_HOST'] . '/api/v1.0/message/add', ['type' => Message::$MESSAGE_TYPE_LOVE, 'sendUid' => $data['uid'], 'recipientUid' => $recipientUid, 'chainId' => $data['voice_id']]);
                    }
                    if (!empty($uid)) {
                        $value['myLove'] = $this->getLoveMod()->getUseLove($uid, $voiceId);
                    }
                    return api_return(10011, $value);
                } else {
                    return api_return(-2017);
                }
            }
            return api_return(-2017, 'voiceId, uid');
        }

        public function dislove() {
            $data = $this->getParams();
            if (!empty($data) && !empty($data['id'])) {
                $res = $this->getLoveMod()->dislove($data['id']);
                if (false !== $res) {
                    return api_return(10011, $res);
                } else {
                    return api_return(-2017);
                }
            }
        }

        public function audit() {
            $data = $this->getParams();
            if (!empty($data) && !empty($data['id']) && !empty($data['status'])) {
                $res = $this->getVoiceMod()->audit($data['id'], $data['status']);
                if (false !== $res) {
                    return api_return(10011, $res);
                } else {
                    return api_return(-2017);
                }
            }
        }
    }

